/*
 * Copyright 2002-2016 the atnoce.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.onepass.dao;

import com.atnoce.onepass.pojo.DirType;
import com.atnoce.onepass.pojo.DirTypeSync;
import com.atnoce.onepass.utils.Cache;
import com.atnoce.onepass.utils.DbUtils;
import com.atnoce.onepass.utils.QueueType;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author atnoce.com
 * @date 2016/11/4
 * @since 1.0.0
 */
public class DirTypeDao {
    private Statement statement=null;
    DateTimeFormatter f = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    private void initStatement() throws SQLException, ClassNotFoundException{
        if(statement==null){
            statement=DbUtils.getDBConnection().createStatement();
        }
    }
    /**
     * 获取所有分类
     * @return
     * @throws SQLException
     */
    public ObservableList<DirType> getDirTypes() throws SQLException, ClassNotFoundException{
        initStatement();
        ResultSet rs = statement.executeQuery("select * from fenlei where isDelete='false';");
        ObservableList<DirType> oblist= FXCollections.observableArrayList();
        while(rs.next()){
            String id=rs.getString("dirId");
            String name=rs.getString("dirName");
            String sync=rs.getString("sync");
            String isDelete=rs.getString("isDelete");
            String modifyTime=rs.getString("modifyTime");
            oblist.add(new DirType(id, name, rs.getString("createTime"),modifyTime,sync,isDelete));
        }
        return oblist;
    }

    /**
     * 同步时通过此方法获取所有分类<br/>
     * 查询语句：SELECT * FROM fenlei where modifyTime is not NULL
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public List<DirTypeSync> getSyncDirTypes() throws SQLException, ClassNotFoundException {
        PreparedStatement ps = DbUtils.getDBConnection().prepareStatement("SELECT * FROM fenlei where modifyTime is not NULL;");
        ResultSet rs = ps.executeQuery();
        List<DirTypeSync> list=new ArrayList<>();
        while (rs.next()){
            String id=rs.getString("dirId");
            String name=rs.getString("dirName");
            String sync=rs.getString("sync");
            String isDelete=rs.getString("isDelete");
            String modifyTime=rs.getString("modifyTime");
            String createTime=rs.getString("createTime");
            list.add(new DirTypeSync(id, name, createTime,modifyTime,sync,isDelete));
        }
        return list;
    }
    /**
     * 添加分类
     * @param dirType
     * @return
     * @throws SQLException
     */
    public Map<String,Object> addDirType(DirType dirType) throws SQLException, ClassNotFoundException{
        Map<String,Object> map=new HashMap<>();
        initStatement();
        PreparedStatement ps=DbUtils.getDBConnection().prepareStatement("select * from fenlei where dirName=?;");
        ps.setString(1, dirType.getDirName());
        ResultSet rs = ps.executeQuery();
        if(rs.next()){
            rs.close();
            ps.close();
            map.put("flag", false);
            map.put("msg", "分类已存在");
            return map;
        }
        ps.close();
        ps=DbUtils.getDBConnection().prepareStatement("insert into fenlei values (?,?,?,?,?,?);");
        ps.setString(1, dirType.getDirId());
        ps.setString(2, dirType.getDirName());
        ps.setString(3, dirType.getCreateTime());
        ps.setString(4, dirType.getModifyTime());
        ps.setString(5, dirType.getSync());
        ps.setString(6,dirType.getIsDelete());
        //如果第一个结果是 ResultSet 对象，则返回 true；如果第一个结果是更新计数或者没有结果，则返回 false
        ps.execute();
        int updateCount = ps.getUpdateCount();
        if(updateCount==1){
            map.put("flag", true);
        }
        return map;
    }
    /**
     * 删除分类
     * @param dirName
     * @return
     * @throws SQLException
     */
    public boolean deleteDirType(String dirName) throws SQLException, ClassNotFoundException{
        PreparedStatement ps=DbUtils.getDBConnection().prepareStatement("update fenlei set isDelete='true' where dirName=?;");
        ps.setString(1, dirName);
        ps.execute();
        int updateCount = ps.getUpdateCount();
        if(updateCount==1){
            DirType dirTypeByName = getDirTypeByName(dirName);
            if (dirTypeByName!=null){
                Map<QueueType,String> queue=new HashMap<>();
                queue.put(QueueType.DIRCLASS,dirTypeByName.getDirId());
                Cache.addUpdateModifyTimeQueue(queue);
            }
            return true;
        }
        return false;
    }
    /**
     * 重命名分类名称
     * @param oldName
     * @param newName
     * @return
     * @throws SQLException
     */
    public boolean renameDirType(String oldName,String newName) throws SQLException, ClassNotFoundException{
        PreparedStatement ps= DbUtils.getDBConnection().prepareStatement("update fenlei set dirName=?,modifyTime=?,sync=? where dirName=?;");
        ps.setString(1, newName);
        ps.setString(2, null);
        ps.setString(3, "false");
        ps.setString(4,oldName);
        ps.executeUpdate();
        int updateCount = ps.getUpdateCount();
        if(updateCount==1){
            return true;
        }
        return false;
    }

    /**
     * 更新分类信息
     * @param dirType
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public boolean updateDirType(DirType dirType) throws SQLException, ClassNotFoundException {
        PreparedStatement ps=DbUtils.getDBConnection().prepareStatement("update fenlei set dirName=?,createTime=?,modifyTime=?,sync=?,isDelete=? where dirId=?");
        ps.setString(1,dirType.getDirName());
        ps.setString(2,dirType.getCreateTime());
        ps.setString(3,dirType.getModifyTime());
        ps.setString(4,dirType.getSync());
        ps.setString(5,dirType.getIsDelete());
        ps.setString(6,dirType.getDirId());
        ps.executeUpdate();
        int updateCount = ps.getUpdateCount();
        if (updateCount==1){
            return true;
        }
        return false;
    }

    public void updateModifyTime(String s, String time) throws SQLException, ClassNotFoundException {
        PreparedStatement ps = DbUtils.getDBConnection().prepareStatement("SELECT * FROM fenlei where dirId=?;");
        ps.setString(1,s);
        ResultSet rs = ps.executeQuery();
        DirType type=null;
        while (rs.next()){
            String id=rs.getString("dirId");
            String name=rs.getString("dirName");
            String sync=rs.getString("sync");
            String isDelete=rs.getString("isDelete");
            String modifyTime=rs.getString("modifyTime");
            String createTime=rs.getString("createTime");
            type=new DirType(id, name, createTime,modifyTime,sync,isDelete);
        }
        if (type!=null){
            type.setModifyTime(time);
            updateDirType(type);
        }
    }

    public DirType getDirTypeByName(String trim) throws SQLException, ClassNotFoundException {
        PreparedStatement ps=DbUtils.getDBConnection().prepareStatement("SELECT * FROM fenlei WHERE dirName=?;");
        ps.setString(1,trim);
        ResultSet rs=ps.executeQuery();
        DirType type=null;
        while (rs.next()){
            String id=rs.getString("dirId");
            String name=rs.getString("dirName");
            String sync=rs.getString("sync");
            String isDelete=rs.getString("isDelete");
            String modifyTime=rs.getString("modifyTime");
            String createTime=rs.getString("createTime");
            type=new DirType(id, name, createTime,modifyTime,sync,isDelete);
        }
        return type;
    }
}
